package com.panda.pandawash.fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanRecord;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.panda.pandawash.bean.BindDevicesBean;
import com.panda.pandawash.util.ProductsListUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.panda.pandawash.R;
import com.panda.pandawash.activity.DeviceScanActivity;
import com.panda.pandawash.activity.MotorMonitorActivity;
import com.panda.pandawash.adapter.AdapterBindDevicesList;
import com.panda.pandawash.adapter.AdapterPopWindowList;
import com.panda.pandawash.api.ApplicationConstant;
import com.panda.pandawash.application.CDApplication;
import com.panda.pandawash.util.PermissionUtils;
import com.panda.pandawash.util.SelfDialog;
import com.panda.pandawash.view.LoadingDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;


public class DeviceFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";

    // TODO: Rename and change types of parameters
    private String mParam1;

    private OnFragmentInteractionListener mListener;

    private SimpleAdapter adapter;//add by gwf.
    private LinearLayout linearLayout;//add device. gwf

    public DeviceFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment DeviceFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static DeviceFragment newInstance() {
        DeviceFragment fragment = new DeviceFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
        }


    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        linearLayout = (LinearLayout) getActivity().findViewById(R.id.add_device_layout);
        linearLayout.setOnClickListener(mClickListener);
    }
    View view;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_device, container, false);

        /// 移植. @{
        init(view);
        mHandler = new Handler();

        final BluetoothManager bluetoothManager = (BluetoothManager) getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        if (mBluetoothAdapter == null) {

            Toast.makeText(getActivity(), R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
            getActivity().finish();
        }
        /// @}
        myAdapterBindDevicesList = new AdapterBindDevicesList(dataList, getActivity());//建立表格，添加表格内容
        bindDeviceListView.setAdapter(myAdapterBindDevicesList);//将表格添加到列表框

        if (Build.VERSION.SDK_INT >= 21) {
            scanCallback = new ScanCallback() {
                @Override
                public void onScanResult(int callbackType, ScanResult result) {
                    if (callbackType != ScanSettings.CALLBACK_TYPE_ALL_MATCHES) {
                        // Should not happen.
                        Log.e(TAG, "scanCallback--1--LE Scan has already started");
                        return;
                    }
                    ScanRecord scanRecord = result.getScanRecord();
                    if (scanRecord == null) {
                        Log.e(TAG, "scanCallback--2--scanRecord is null.");
                        return;
                    }

                    mLeScanCallback.onLeScan(result.getDevice(), result.getRssi(),
                            scanRecord.getBytes());
                }

                @Override
                public void onBatchScanResults(List<ScanResult> results) {
                    for (ScanResult sr : results) {
                        Log.i(TAG, "onBatchScanResults--" + sr.toString());
                    }
                }

                @Override
                public void onScanFailed(int errorCode) {
                    Log.e(TAG, "onScanFailed--Error Code: " + errorCode);
                }
            };
        }
        return view;
    }

    /// 移植. @{
    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (productsWindow != null) {
            productsWindow.dismiss();
        }
        //init(view);
        if (!mBluetoothAdapter.isEnabled()) {
            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        } else {
            stop_timer();
            timer = new Timer();
            task = new MyTimerTask();
            timer.schedule(task, 1000, TIMER_PERIOD);
        }
        if (bindDevicesIsChanged()) {
            LookForBindDevices();
            //initDevicesList();
        }

        initDevicesList();
    }
    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        stop_timer();
        if (mScanning)
            scanLeDevice(false);
    }
    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        stop_timer();
        if (mScanning)
            scanLeDevice(false);
    }
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        stop_timer();
        if (mScanning)
            scanLeDevice(false);
    }
    /// @}

    private List<? extends Map<String, ?>> getData(
            int[] icon1, String[] above, String[] below, String[] icon2) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        //Device device1 = new Device();
        for (int i = 0; i < 10; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("oil_box", icon1[i]);
            map.put("title", above[i]);
            map.put("info", below[i]);
            map.put("need_oil", icon2[i]);
            list.add(map);
        }
        return list;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    private View.OnClickListener mClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.add_device_layout:
                    if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M) {
                        if (!PermissionUtils.isLocationEnable(getActivity())) {
                            requestDialog(getActivity());
                        }else{
                            PermissionUtils.locationCheck(getActivity());
                            if(PermissionUtils.locationPermission){
                                Intent myIntent = new Intent();
                                myIntent.setClass(getActivity(), DeviceScanActivity.class);
                                startActivity(myIntent);
                            }

                        }
                    }else {
                        Intent intent = new Intent(getActivity(), DeviceScanActivity.class);
                        startActivity(intent);
                    }
                    break;
            }
        }
    };

    /// ==================== 代码移植  =========================

    private String TAG = "BindDevicesFragment";
    private ImageView addDevices;
    private PopupWindow productsWindow;
    private ListView popListProducts;
    private ListView bindDeviceListView;
    private String mDeviceName;
    private String mDeviceAddress;
    private int mDeviceModel;
    private List<BindDevicesBean> myDevicesList;
    private final List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();			//数据列表
    private final List<Map<String, Object>> searchForList = new ArrayList<Map<String, Object>>();	//搜索列表
    private List<Map<String, Object>> updateList;		//更新列表
    private List<Map<String, Object>> cacheList;		//缓存列表

    private SelfDialog mSelfDialog;
    //private UnBindDialog mUnBindDialog;
    private BluetoothAdapter mBluetoothAdapter;
    private LoadingDialog dialog;
    private Handler mHandler;
    private static final int REQUEST_ENABLE_BT = 1;
    private static final long SCAN_PERIOD = 3000;  //配置搜索时间
    private static final long TIMER_PERIOD = SCAN_PERIOD + 1000;
    private boolean mScanning;
    private int DEVICE_LIST_UPDATE = 0X100;

    private static final int DEVICE_ALIVE_TIME = 5000;
    private static final String DEVICE_SCAN_TIME = "scanTime";
    private AdapterBindDevicesList myAdapterBindDevicesList;
    private ScanCallback scanCallback;


    Handler deviceUpdateHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            if (msg.what == DEVICE_LIST_UPDATE) {
                /*如果搜索列表里有内容*/
                if (false/*searchForList != null && searchForList.size() != 0*/) {
                    for (int i = 0; i < dataList.size(); i++) {
                        boolean flg = false;
                        for (int j = 0; j < searchForList.size(); j++) {
                            /*
							dataList里的地址和searchForList里的地址吻合
							返回 true
							*/
                            if (dataList.get(i).get(MotorMonitorActivity.EXTRAS_DEVICE_ADDRESS)
                                    .equals(searchForList.get(j).get(MotorMonitorActivity.EXTRAS_DEVICE_ADDRESS))) {
                                flg = true;
                            }
                        }

                        if (flg) {//有保存的地址
                        } else {
                            HashMap<String, Object> map = new HashMap<String, Object>();
                            map.put(MotorMonitorActivity.EXTRAS_DEVICE_NAME, dataList.get(i)
                                            .get(MotorMonitorActivity.EXTRAS_DEVICE_NAME));
                            map.put(MotorMonitorActivity.EXTRAS_DEVICE_ADDRESS, dataList.get(i)
                                            .get(MotorMonitorActivity.EXTRAS_DEVICE_ADDRESS));
                            map.put(MotorMonitorActivity.EXTRAS_DEVICE_MODEL, myDevicesList.get(i).getModel());
                            map.put("near_by", 0);
                            dataList.set(i, map);
                        }
                    }
                    initDevicesList();//初始化显示驱动设备列表

                }
                scanLeDevice(true);//扫描蓝牙设备 3秒后停止
            }
        }

    };

    private void refreshDataAfterScan() {
        int i, j;

        LookForBindDevices();

        if (searchForList != null && searchForList.size() != 0) {
            for (i = 0; i < dataList.size(); i++) {
                for (j = 0; j < searchForList.size(); j++) {
                    if (dataList
                            .get(i)
                            .get(MotorMonitorActivity.EXTRAS_DEVICE_ADDRESS)
                            .equals(searchForList
                                    .get(j)
                                    .get(MotorMonitorActivity.EXTRAS_DEVICE_ADDRESS))) {
                        break;
                    }
                }

                if (j < searchForList.size()) {
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    map.put(MotorMonitorActivity.EXTRAS_DEVICE_NAME,
                            dataList.get(i)
                                    .get(MotorMonitorActivity.EXTRAS_DEVICE_NAME));
                    map.put(MotorMonitorActivity.EXTRAS_DEVICE_ADDRESS,
                            dataList.get(i)
                                    .get(MotorMonitorActivity.EXTRAS_DEVICE_ADDRESS));
                    map.put(MotorMonitorActivity.EXTRAS_DEVICE_MODEL,
                            myDevicesList.get(i).getModel());
                    map.put("near_by", (isDeviceAliveInSearchList(j) ? 1 : 0));
                    dataList.set(i, map);
                }
            }
        }

        initDevicesList();
    }

    private boolean isDeviceAliveInSearchList(int j) {
        Map<String, Object> searchMap = (Map<String, Object>)searchForList.get(j);
        if (searchMap == null)
            return false;

        Long old_time_Long = (Long)searchMap.get(DEVICE_SCAN_TIME);
        if (old_time_Long == null)
            return false;

        long old_time = old_time_Long.longValue();
        long cur_time = SystemClock.elapsedRealtime();

        Log.i(TAG, "isDeviceAliveInSearchList--1--the device[ " + j + "], old_time is " + old_time + ", cur_time is " + cur_time);
        return (old_time == 0 || cur_time - old_time <= DEVICE_ALIVE_TIME);
    }

    Timer timer = new Timer();//新建一个定时器
    MyTimerTask task = new MyTimerTask();

    class MyTimerTask extends TimerTask {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            Message msg = new Message();
            msg.what = DEVICE_LIST_UPDATE;
            deviceUpdateHandler.sendMessage(msg);
        }
    }

    private void showProductsList(View v) {

        if (productsWindow == null) {

            LayoutInflater myInflater = LayoutInflater.from(getActivity());
            View myView = myInflater.inflate(R.layout.popwindow_products, null);
            productsWindow = new PopupWindow(myView, LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT);
            ImageView popBtnCancel = (ImageView) myView.findViewById(R.id.view_cancel);
            popBtnCancel.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    productsWindow.dismiss();
                }
            });

            popListProducts = (ListView) myView.findViewById(R.id.list_products);

            ProductsListUtils productsListUtils = new ProductsListUtils(
                    getActivity());
            AdapterPopWindowList myAdapterPopWindowList = new AdapterPopWindowList(
                    productsListUtils.getProductsList(), getActivity());
            popListProducts.setAdapter(myAdapterPopWindowList);
            popListProducts.setItemsCanFocus(false);
            popListProducts.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
            popListProducts.setOnItemClickListener(listClickListener);
        }
        productsWindow.setFocusable(true);
        productsWindow.update();
        productsWindow.showAtLocation(v, Gravity.TOP, 0, 0);

    }

    AdapterView.OnItemClickListener listClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            switch (parent.getId()) {
                case R.id.list_products:
                    //mDeviceModel = position;
                    // check location permission
                    if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M) {
                        if (!PermissionUtils.isLocationEnable(getActivity())) {
                            requestDialog(getActivity());
                        }else{
                            if (!PermissionUtils.locationPermission) {
                                PermissionUtils.locationCheck(getActivity());
                            }else{
                                Intent myIntent = new Intent();
                                myIntent.setClass(getActivity(), DeviceScanActivity.class);
                                startActivity(myIntent);

                            }

                        }
                    }
                    break;
                case R.id.bind_devices_list:
                    mDeviceName = dataList.get(position).get(MotorMonitorActivity.EXTRAS_DEVICE_NAME).toString();
                    mDeviceAddress = dataList.get(position).get(MotorMonitorActivity.EXTRAS_DEVICE_ADDRESS).toString();
                    mDeviceModel = Integer.valueOf(dataList.get(position).get(MotorMonitorActivity.EXTRAS_DEVICE_MODEL).toString());
                    int mDeviceNearBy = Integer.valueOf(dataList.get(position).get("near_by").toString());
                    if (mDeviceNearBy == 1) {
                        Intent connectIntent = new Intent();
                        connectIntent.setClass(getActivity(), MotorMonitorActivity.class);
                        connectIntent.putExtra(MotorMonitorActivity.EXTRAS_DEVICE_MODEL, mDeviceModel);
                        connectIntent.putExtra(MotorMonitorActivity.EXTRAS_DEVICE_NAME, mDeviceName);
                        connectIntent.putExtra(MotorMonitorActivity.EXTRAS_DEVICE_ADDRESS, mDeviceAddress);
                        startActivity(connectIntent);
                    } else {
                        Toast.makeText(getActivity(), "no_search_device", Toast.LENGTH_SHORT).show();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    AdapterView.OnItemLongClickListener onItemLongClickListener = new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            switch (parent.getId()) {
                case R.id.bind_devices_list:
                    showDialog(position);
                    break;
                default:
                    break;
            }

            return true;
        }
    };

    private void showDialog(final int i) {
        mSelfDialog = new SelfDialog(getActivity());
        Window mWindow = mSelfDialog.getWindow();
        WindowManager.LayoutParams lp = mWindow.getAttributes();
        mWindow.setGravity(Gravity.CENTER);

        mSelfDialog.setTitle("是否解除绑定？");
        mSelfDialog.setMessage("确定退出应用?");
        mSelfDialog.setEditVisibility(View.GONE);
        mSelfDialog.setYesOnclickListener("确定",
                new SelfDialog.onYesOnclickListener() {

                    @Override
                    public void onYesClick(Object data, boolean flg) {
                        // TODO Auto-generated method stub
                        deleteBindDevice(i);
                        // init(myView);
                        LookForBindDevices();
                        initDevicesList();
                        mSelfDialog.dismiss();
                    }
                });
        mSelfDialog.setNoOnclickListener("取消",
                new SelfDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {

                        mSelfDialog.dismiss();
                    }
                });
        mSelfDialog.show();
    }

    private void deleteBindDevice(int position) {
        String deleteAddress = dataList.get(position).get(MotorMonitorActivity.EXTRAS_DEVICE_ADDRESS).toString();
        DbUtils dbUtils = CDApplication.getIntance().getDbUtil();
        try {
            BindDevicesBean bindDevicesBean = dbUtils.findFirst(Selector.from(
                    BindDevicesBean.class).where("mac_address", "=", deleteAddress));
            int id = bindDevicesBean.getId();
            dbUtils.delete(bindDevicesBean);
        } catch (DbException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @SuppressLint("NewApi")
    private void scanLeDevice(final boolean enable) {
        if (enable) {
            		/*	启动一个定时时间为SCAN_PERIOD秒的定时器事件
				在这里为3秒每次来触发Runnable方法
			*/
            mHandler.removeCallbacksAndMessages(null);
            mHandler.postDelayed(new Runnable() {
                @SuppressLint("NewApi")
                @Override
                public void run() {
                    mScanning = false;
                    //mBluetoothAdapter.stopLeScan(mLeScanCallback);//停止扫描设备
                    stopBLEScan(mBluetoothAdapter);
                    Log.i(TAG, "stopLeScan--2--");
                    // dialog.cancel();
                    refreshDataAfterScan();
                }
            }, SCAN_PERIOD);
            mScanning = true;
            //searchForList = new ArrayList<Map<String, Object>>();	//创建一个搜索列表
            //boolean scanRs = mBluetoothAdapter.startLeScan(mLeScanCallback);//扫描蓝牙设备
            boolean scanRs = startBLEScan(mBluetoothAdapter);
            Log.i(TAG, "startLeScan--1--scanRs is " + scanRs);;
        } else {
            mScanning = false;
            mHandler.removeCallbacksAndMessages(null);
            //mBluetoothAdapter.stopLeScan(mLeScanCallback);//停止扫描设备
            stopBLEScan(mBluetoothAdapter);
            Log.i(TAG, "stopLeScan--1--");
            // dialog.cancel();
        }

    }

    public boolean startBLEScan(BluetoothAdapter ba) {
        if (Build.VERSION.SDK_INT >= 21) {
            BluetoothLeScanner mLEScanner = ba.getBluetoothLeScanner();
            if (mLEScanner == null) {
                Log.e(TAG, "startBLEScan--1--the scanner is null.");
                return false;
            }

            ScanSettings settings = new ScanSettings.Builder()
                    //.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
            List<ScanFilter> filters = new ArrayList<ScanFilter>();

            mLEScanner.startScan(filters, settings, scanCallback);
            return true;
        }
        else {
            return ba.startLeScan(mLeScanCallback);
        }
    }

    public boolean stopBLEScan(BluetoothAdapter ba) {
        if (Build.VERSION.SDK_INT >= 21) {
            BluetoothLeScanner mLEScanner = ba.getBluetoothLeScanner();
            if (mLEScanner == null) {
                Log.e(TAG, "stopBLEScan--1--the scanner is null.");
                return false;
            }

            mLEScanner.stopScan(scanCallback);
        }
        else {
            ba.stopLeScan(mLeScanCallback);
        }

        return true;
    }

    private boolean bindDevicesIsChanged() {
        List<BindDevicesBean> bindDevicesList = null;
        DbUtils dbUtils = CDApplication.getIntance().getDbUtil();
        try {
            bindDevicesList = dbUtils.findAll(BindDevicesBean.class);
        } catch (DbException e) {
            return false;
        }

        if (bindDevicesList != null && bindDevicesList.size() != dataList.size()) {
            return true;
        }

        return false;
    }

    private void LookForBindDevices() {
        DbUtils dbUtils = CDApplication.getIntance().getDbUtil();
        try {
            myDevicesList = dbUtils.findAll(BindDevicesBean.class);
        } catch (DbException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //dataList = new ArrayList<Map<String, Object>>();
        Log.i(TAG, "LookForBindDevices--1--the dataList is " + dataList.size());
        dataList.clear();

        if (myDevicesList != null && myDevicesList.size() > 0) {
            for (int i = 0; i < myDevicesList.size(); i++) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                if (myDevicesList.get(i).getPedName() == null) {
                    map.put(MotorMonitorActivity.EXTRAS_DEVICE_NAME, myDevicesList.get(i).getName());
                } else {
                    map.put(MotorMonitorActivity.EXTRAS_DEVICE_NAME, myDevicesList.get(i).getPedName());
                }
                map.put(MotorMonitorActivity.EXTRAS_DEVICE_ADDRESS, myDevicesList.get(i).getMacAddress());
                map.put(MotorMonitorActivity.EXTRAS_DEVICE_MODEL, myDevicesList.get(i).getModel());
                map.put("near_by", 0);
                dataList.add(map);
            }
        }

    }

    private void addDeviceToScanList(BluetoothDevice device) {
        String searchDeviceAddress = device.getAddress();//获取驱动设备的地址
        String searchDeviceName = device.getName();	//获取驱动设备的名字
        Map<String, Object> devicemap = null;
        int i;
        long old_time = 0;
        long cur_time = SystemClock.elapsedRealtime();

        for (i = 0; i < searchForList.size(); i++) {
            Map<String, Object> map = (Map<String, Object>)searchForList.get(i);
            if (map.get(MotorMonitorActivity.EXTRAS_DEVICE_ADDRESS).equals(searchDeviceAddress)) {
                old_time = ((Long)map.get(DEVICE_SCAN_TIME)).longValue();
                devicemap = map;
                break;
            }
        }

        if (devicemap == null) {
            devicemap = new HashMap<String, Object>();
            devicemap.put(MotorMonitorActivity.EXTRAS_DEVICE_NAME, searchDeviceName);
            devicemap.put(MotorMonitorActivity.EXTRAS_DEVICE_ADDRESS, searchDeviceAddress);
            searchForList.add(devicemap);
        }

        Log.i(TAG, "addDeviceToScanList--1--the device is " + searchDeviceAddress + ", old_time is " + old_time + ", cur_time is " + cur_time);
        devicemap.put(DEVICE_SCAN_TIME, new Long(cur_time));

        if (old_time == 0 || cur_time - old_time > DEVICE_ALIVE_TIME) {
            refreshDataAfterScan();
        }
    }

    @SuppressLint("NewApi")
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi,
                             byte[] scanRecord) {
            // TODO Auto-generated method stub

            if (getActivity() == null)
                return;

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    addDeviceToScanList(device);
                }
            });
        }
    };
    private void initDevicesList() {
        //AdapterBindDevicesList myAdapterBindDevicesList = new AdapterBindDevicesList(dataList, getActivity());
        //bindDeviceListView.setAdapter(myAdapterBindDevicesList);
        Log.i(TAG, "initDevicesList--1--the dataList is " + dataList.size());

        myAdapterBindDevicesList.notifyDataSetChanged();
    }
    /*初始化设备显示框*/
    private void init(View v) {
		/*列表框项目条*/
        bindDeviceListView = (ListView) v.findViewById(R.id.bind_devices_list);
        bindDeviceListView.setOnItemClickListener(listClickListener);
        bindDeviceListView.setOnItemLongClickListener(onItemLongClickListener);
        //LookForBindDevices();
        //initDevicesList();
    }

    public void stop_timer() {
        if (task != null) {
            task.cancel(); // 将原任务从队列中移除
            task = null;
        }
        if (timer != null) {
            timer.cancel();
            task = null;
        }
    }

    private void requestDialog(Context context) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(context.getResources().getString(R.string.location_enable_title).toString());
        builder.setMessage(context.getResources().getString(R.string.location_enable_notification).toString());
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, ApplicationConstant.REQUEST_CODE_LOCATION_SETTINGS);
            }
        });
        builder.show();
    }


}
